package com.kordar.auth;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kordar.rbac.AuthManager;
import com.kordar.rbac.Permission;
import com.kordar.rbac.Role;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@DS("#kordardb")
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Admin> implements AuthService {

    AuthManager authManager;

    public void setAuthManager(AuthManager authManager) {
        this.authManager = authManager;
    }

    @Override
    public Admin findOneByUsername(String username) {
        log.debug("查询用户：-----" + username);
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return getOne(wrapper);
    }

    @Override
    public Set<String> findRolesByUser(long userId) {
        return authManager.getRolesByUser(userId).stream().map(Role::getName).collect(Collectors.toSet());
    }

    @Override
    public Set<String> findPermissionsByUser(long userId) {
        return authManager.getPermissionsByUser(userId).stream().map(Permission::getName).collect(Collectors.toSet());
    }

    @Override
    public Set<String> findRolesByUser(Admin admin) {
        if (admin.getType().equals(Admin.SUPER_ADMIN)) {
            System.out.println(authManager.getRoles());
            return authManager.getRoles().stream().map(Role::getName).collect(Collectors.toSet());
        }
        return authManager.getRolesByUser(admin.getId()).stream().map(Role::getName).collect(Collectors.toSet());
    }

    @Override
    public Set<String> findPermissionsByUser(Admin admin) {
        if (admin.getType().equals(Admin.SUPER_ADMIN)) {
            return authManager.getPermissions().stream().map(Permission::getName).collect(Collectors.toSet());
        }
        return authManager.getPermissionsByUser(admin.getId()).stream().map(Permission::getName).collect(Collectors.toSet());
    }
}
